import 'dart:convert';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:test_flutter/cache/UserDataCache.dart';
import 'package:test_flutter/constant/resources.dart';
import 'package:test_flutter/dio/Api.dart';
import 'package:test_flutter/dio/DioUtil.dart';
import 'package:test_flutter/model/response/car_model.dart';
import 'package:test_flutter/model/response/user_model.dart';
import 'package:test_flutter/pages/edite_info.dart';
import 'package:test_flutter/utils/ToastUtil.dart';
import 'package:test_flutter/utils/common_utils/CustomLocalizations.dart';
import 'package:test_flutter/utils/factory/Fit.dart';
import 'package:flutter/services.dart';
import 'package:test_flutter/utils/util.dart';


class CardManagerPage extends StatefulWidget {
  final String title;
  CardManagerPage(this.title);
  @override
  CardManagerPageState createState() => new CardManagerPageState();
}

class CardManagerPageState extends State<CardManagerPage> {
  bool _saving = false;
  String mCardNo;
  List list = new List();

  void _updateData() {
    for (int i = 0, length = list.length; i < length; i++) {
      list[i]['IsDefault'] = (list[i]['CardNo'] == mCardNo);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMemberCardList();
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: new ThemeData(
        primarySwatch: Colors.grey,
        brightness: Brightness.light,
      ),
      child: new Scaffold(
        backgroundColor: Colors.white,
        appBar: PreferredSize(
            child: Container(
              color: Color(0xFFD5AE75),
              child: new AppBar(
                primary: true,
                title: new Text(widget.title),
                backgroundColor: Colors.transparent,
              ),
            ),
            preferredSize: new Size(Fit.scaleX(1080), kToolbarHeight)),
        body: ModalProgressHUD(
          inAsyncCall: _saving,
          child: Container(
            margin: EdgeInsets.only(top: Fit.scaleX(60)),
            color: Colors.white,
            child: new ListView.builder(
                itemCount: list.length,
                itemBuilder: (BuildContext context, int index) {
                  String cardNo = list[index]['CardNo'];
                  return new Container(
                    child: new Column(
                      children: <Widget>[
                        Container(
                          width: Fit.scaleX(1000),
                          height: Fit.scaleY(350),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(Fit.scaleX(30)),
                            color: Color(0xFFD5AE75),
                          ),
                          child: ListTile(
                            contentPadding: EdgeInsets.all(0.0),
                            title: Container(
                              width: Fit.scaleX(350),
                              height: Fit.scaleY(350),
                              padding: EdgeInsets.only(left: Fit.scaleX(30),top: Fit.scaleX(30)),
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Padding(
                                    padding:EdgeInsets.only(top: Fit.scaleX(20)),
                                    child: Text(
                                      CustomLocalizations.instance.getString(StringIds.cardNum)+': ${list[index]['CardNo']}',
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                          fontSize: Fit.scaleTextSize(48), color: Colors.black54),
                                    ),
                                  ),
                                  Padding(
                                    padding:EdgeInsets.only(top: Fit.scaleX(20)),
                                    child: Text(
                                      CustomLocalizations.instance.getString(StringIds.category)+': ${list[index]['LevelName']}',
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                          fontSize: Fit.scaleTextSize(48), color: Colors.black54),
                                    ),
                                  ),
                                  Padding(
                                    padding:EdgeInsets.only(top: Fit.scaleX(20)),
                                    child: Text(
                                      CustomLocalizations.instance.getString(StringIds.sum)+': ${list[index]['Balance']}',
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                          fontSize: Fit.scaleTextSize(48), color: Colors.black54),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            trailing: Radio(
                                value: true,
                                groupValue: list[index]['IsDefault'] == true,
                                activeColor: Colors.green,
                                onChanged: (value) {
                                  print('select:  $index');

                                  mCardNo = cardNo;
                                  _updateData();
                                }),
                            onTap: () {
                              int Id = list[index]['Id'];
                              _setDefaultCard(Id, cardNo);
                            },
                          ),
                        ),
                        new Divider()
                      ],
                    ),
                  );
                }),
          ),
        ),
        floatingActionButton: new Builder(builder: (BuildContext context) {
          return new FloatingActionButton(
            child: const Icon(Icons.add),
            tooltip: "Hello",
            foregroundColor: Colors.white,
            backgroundColor: Colors.orange,
            heroTag: null,
            elevation: 7.0,
            highlightElevation: 14.0,
            onPressed: () {
              /*Scaffold.of(context).showSnackBar(new SnackBar(
                  content: new Text("FAB is Clicked"),
                ));*/
             // scan();
              judgeUserInfo();
            },
            mini: false,
            shape: new CircleBorder(),
            isExtended: false,
          );
        }),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }


  ///判断用户信息是否完善，诺完善，打开二维码扫描界面  ；  诺没完善，打开信息完善界面
  Future<bool> judgeUserInfo() async{
    DioUtil.getInstance(context).post(
        Api.bindMemberCardCheck, (response) {
            if (response.data['code'] == 1) {
              scan();
            } else {
              _goComplateInfo();
            }
    });

  }






  ///二维码扫描
  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      print('二维码: $barcode');


      String decryptedString = await util.decrypted(barcode);
      print("解密会员卡: $decryptedString");


      CarModel carModel = CarModel.fromJson(json.decode(decryptedString));
      _addMemberCard(carModel);
      //ToastUtil.showToast(barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        ToastUtil.showToast('The user did not grant the camera permission!');
      } else {
        ToastUtil.showToast('Unknown error: $e');
      }
    }on Exception catch (e)  {
      if(e.toString().contains('Invalid envelope')){
        ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.cancelScan));
      }
      if(e.toString().contains('Unexpected character')){
        ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.invalidQrCode));
      }
    }
  }

  ///绑定会员卡
  _addMemberCard(CarModel carModel) async {
    setState(() {
      _saving = true;
    });

    Map<String, String> requestMap = new Map();
    UsersModel user = await UserDataCache.getInstance().getUser();
    requestMap['MobileNo'] = user.MobileNo;
    requestMap['CardId'] = carModel.cid;
    requestMap['CardNo'] = carModel.cno;
    requestMap['Shop'] = carModel.shop;
    requestMap['Term'] = carModel.term;

    DioUtil.getInstance(context).post(
        Api.addMemberCard,
        (response) {
          if (response.data['code'] == 1) {
            ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.membershipCardBindingSuccessful));
            _getMemberCardList();
          } else {
            ToastUtil.showToast(response.data['msg']);
          }
          setState(() {
            _saving = false;
          });
        },
        data: requestMap,
        errorCallBack: (errorMsg) {
          print("error=========================:" + errorMsg);
          ToastUtil.showToast(errorMsg);
          setState(() {
            _saving = false;
          });
        });
  }

  ///获取会员卡列表
  _getMemberCardList() async {
    setState(() {
      _saving = true;
    });
    DioUtil.getInstance(context).get(Api.getMemberCardList, (response) {
      if (response.data['code'] == 1) {
        list = response.data['data']['list'];

        setState(() {});
      } else {
        ToastUtil.showToast(response.data['msg']);
      }

      setState(() {
        _saving = false;
      });
    }, errorCallBack: (errorMsg) {
      print("error=========================:" + errorMsg);
      ToastUtil.showToast(errorMsg);
      setState(() {
        _saving = false;
      });
    });
  }

  ///设置默认卡
  _setDefaultCard(int id, String cardNo) async {
    setState(() {
      _saving = true;
    });

    Map<String, int> requestMap = new Map();
    requestMap['Id'] = id;

    DioUtil.getInstance(context).post(
        Api.setDefaultCard,
        (response) {
          if (response.data['code'] == 1) {
            setState(() {
              mCardNo = cardNo;
              _updateData();
            });
          } else {
            ToastUtil.showToast(response.data['msg']);
          }
          setState(() {
            _saving = false;
          });
        },
        data: requestMap,
        errorCallBack: (errorMsg) {
          print("error=========================:" + errorMsg);
          ToastUtil.showToast(errorMsg);
          setState(() {
            _saving = false;
          });
        });
  }

  Future<Null> _goComplateInfo() async {
    return showDialog<Null>(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(CustomLocalizations.instance.getString(StringIds.pleaseCompleteTheInformationFirst)),
          actions: <Widget>[
            FlatButton(
              child: Text(CustomLocalizations.instance.getString(StringIds.cancel)),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
              child: Text(CustomLocalizations.instance.getString(StringIds.confirm)),
              onPressed: () {
                Navigator.of(context).pop();
                //跳转完善信息
                Navigator.push<Object>(context,
                    new MaterialPageRoute(
                        builder: (BuildContext context) {
                          return new EditInfoPage();
                        }));
              },
            ),
          ],
        );
      },
    );
  }

}
